<?php
namespace app\agent\controller\cash;

use app\agent\controller\Controller;
use app\agent\model\agent\Agent as AgentModel;
use app\agent\model\agent\User as AgentUserModel;
use app\agent\model\wxapp\Wxapp as WxappModel;
use think\Db;
use think\Session;

class Cash extends Controller{
    /**
     * 提现首页
     */
    public function index(){
        $session = Session::get('yoshop_agent');
        $agent_id = $session['agent']['agent_id'];
        $model = new WxappModel;
        $page=isset($pagenum)&&is_numeric(input('post.page_num'))?intval($pagenum):1;
        $limit = 10;
        $offset=($page-1) * $limit;
        $arr=['in','0,1,2'];
        return $this->fetch('index', [
            'list' => $list = $model->getOrderList($agent_id,$page,$offset,$arr),
        ]);
    }
    /*
     * 申请提现
     */
    public function add(){
        $session = Session::get('yoshop_agent');
        $agent_id = $session['agent']['agent_id'];
        $yifen=Db::name('divide_service')->where(['agent_id'=>$agent_id,'status'=>1])->sum('amount');
        //$daifenfen=Db::name('divide_service')->where(['agent_id'=>$agent_id,'status'=>0])->sum('amount');
        //余额 为已分账的总金额减去 提现成功/待审核的总金额
        $money=Db::name('agent_cashout')->where(['agent_id'=>$agent_id,'sh_status'=>['<',2]])->sum('money');
        $yue=$yifen-$money;
        if (!$this->request->isAjax()) {
            //获取余额
            $info=Db::name('base_setting')->where(['key'=>'invoice'])->find();
            $this->assign('config',json_decode($info['values'],'true'));
            $this->assign('yue',$yue);
            return $this->fetch('add');
        }
        //判断当前提现金额是否大于余额
        $this->assign('yue',$yue);
        $data = $this->postData('agent');
        if(empty($data['money'])){
            return $this->renderError('请输入提现金额');
        }
        if($data['money']>$yue){
            return $this->renderError('提现金额不能大于余额');
        }
        //将提现信息写入agent_cashout表
        if($data['isKaipiao']){
            $rel_money=bcsub($data['money']*0.93, 0, 2);
        }else{
            $rel_money=0;
        }
        $dataInfo['money']=$data['money'];
        $dataInfo['sh_status']=0;//总后台审核  0：待通过 1：已冻结 2：通过
        $dataInfo['create_time']=time();
        $dataInfo['pps_status']=0;//品牌商审核  0：待通过 1：通过 2：拒绝 3：待解冻
        $dataInfo['pps_update_time']=0;
        $dataInfo['sh_update_time']=0;
        $dataInfo['agent_id']=$agent_id;
        $dataInfo['remark']='';
        $dataInfo['rel_money']=$rel_money;
        $dataInfo['isKaipiao']=$data['isKaipiao'];
        Db::name('agent_cashout')->insertGetId($dataInfo);
        return $this->renderSuccess('申请成功',url('cash.cash/index'));
    }
}